<?php 
$req_path="./";
include_once($req_path."include/ini.php");
require_once($req_path."include/db.php");
class M_stock extends DB{
	private $rowCount="0";
	private $ID="0";
	private $totalpage="0";
	
	function M_stock(){
		parent::__construct();
	}
	function getRowCount(){
		return $this->rowCount;
	}
	function getListPage(){
		global $list_page;
		return $list_page;
	}
	function getTotalPage(){
		return $this->totalpage;
	}
	function convertStock($pid){
		$sql = 'SELECT coalesce(Scale ,1) Scale
				FROM tb_product
				Where ID ='.$pid.' and SubUnit <> 0';
				
		$result=$this->ExecuteData($sql);
		$count= $result->RecordCount();
		if ($count>0){
			$row=$result->FetchRow();
			return $row['Scale'];
		}else{
			return 1;
		}
	}	
	//Manage Stock
	function UpdateStock($pid, $branchid, $amt=0, $user=""){
		// Exist update
		$scal = $this->convertStock($pid);
		
		if ($this->checkStock($pid,$branchid)){
			$sqlupdate=" update tb_stock_product "
						. " set Amount= Amount+".($scal * $amt)
						. " , MainAmt= ((Amount) - ((Amount)%".$scal ."))/".$scal 
						. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
						. " , UpdatedBy='".$user."'"
						. " Where BranchID=".$branchid 
						. " And ProductID=".$pid;
			$this->ExecuteData($sqlupdate);
 		}else{ // not exists insert
			$sqlInsert=" Insert into tb_stock_product(BranchID, ProductID, Amount, MainAmt, UpdatedDate, UpdatedBy)";
			$sqlInsert.="values (".$branchid.",".$pid.",".($scal * $amt).",".$amt.",Now(),'".$user."') ";
			$this->ExecuteData($sqlInsert);
		}
	} 
	function UpdateReturnStockBranch($pid, $branchid, $amt=0, $user="",$IsAdd=1){
		$scal = $this->convertStock($pid);
		if ($IsAdd==1){
			
			$sqlupdate=" update tb_stock_product "
				. " set Amount= Amount + ".($scal* $amt)
				. " , MainAmt= ((Amount) - ((Amount)%".$scal ."))/".$scal 
				. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
				. " , UpdatedBy='".$user."'"
				. " Where BranchID=".$branchid 
				. " And ProductID=".$pid;
		}else{
			$sqlupdate=" update tb_stock_product "
				. " set Amount= Amount - ".($scal* $amt)
				. " , MainAmt=  ((Amount) - ((Amount)%".$scal ."))/".$scal 
				. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
				. " , UpdatedBy='".$user."'"
				. " Where BranchID=".$branchid 
				. " And ProductID=".$pid;
		}	
		$this->ExecuteData($sqlupdate);
	}
	 
	function UpdateReturnStockDefect($pid, $branchid, $amt=0, $user=""){
			$sqlInsert=" Insert into tb_stock_product_defect(Branch, Product, Amount, CreatedDate, CreatedBy)";
			$sqlInsert.="values (".$branchid.",".$pid.",".$amt.",Now(),'".$user."') ";
			$this->ExecuteData($sqlInsert);	
	}
	function GetHO_ID(){ 
		$sqlBranch = 'select id from tb_branch b where b.Type=1 and IsActived=1' ;
		$result = $this->ExecuteData($sqlBranch);
		$rBranch = $result->FetchRow();
		return $rBranch['id'];
	}
	//update stock at HO
	function MoveFromTempStock($pid,$amt=0,$HO=0){
		$scal = $this->convertStock($pid);
		$sqlupdate=" update tb_stock_product "
				." set Amount = Amount + (".$scal * $amt.")"
				." , MainAmt=  ((Amount) - ((Amount)%". $scal ."))/".$scal 
				. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
				. " , UpdatedBy='".$user."'"				
				." where BranchID=".$HO." and ProductID=".$pid;
				
		$this->ExecuteData($sqlupdate);	
	}
	
	function getStockProduct($branchid=0, $productname="", $category=0, $type=0,$pageStart=1,$pos=1, $stock=1,$premium=0){
		global $list_page;
		$sqlscript= "select p.ID,b.BranchName ,s.BranchID , p.ProductName, Category, c.CatName , p.Type"
				.", t.Type ProductType ,s.ProductID "
				.", un.Unit , s.Amount, s.MainAmt as mAmount "
				.",  subun.Unit as SubUnit, p.Scale "
				.", p.Price as Sell_Price , p.Cost_Price , p.Cost_branch "
				.", IsStock , IsPremium , IsPOS, p.LimitNumber "
				." From tb_stock_product s "
				." JOIN tb_branch b on b.ID=s.BranchID "
				." JOIN tb_product p on s.ProductID=p.ID "
				." LEFT JOIN tb_product_category c on c.CatID=p.Category"
				." LEFT JOIN tb_product_type t on t.ID=p.Type "
				." LEFT JOIN tb_units un on un.ID=p.MainUnit "
				." LEFT JOIN tb_units subun on  subun.ID=p.SubUnit "
				." Where 1=1 and p.IsDeleted=0 ";
		
		if ($pos==1){
			$sqlscript.= " and p.IsPOS =1";
		}
		if ($stock==1){
			$sqlscript.= " and p.IsStock=1";
		}
		if ($premium==1){
			$sqlscript.= " and p.IsPremium=1";
		}
		
		if (isset($branchid) && $branchid!=0){
			$sqlscript.= " and b.ID =". $branchid;
		}
		if (isset($productname) && $productname!=""){
			$sqlscript.= " and ProductName Like '%". $productname."%'";
		}
		if (isset($category) && $category!=0){
			$sqlscript.= " and p.category =". $category;
		}
		if (isset($type) && $type!=0){
			$sqlscript.= " and p.Type =". $type;
		}
		$sqlscript.= " order by  b.BranchName  , p.ProductName ";
		//Execute
		$result = $this->ExecuteData($sqlscript);
		//Get all rows
		$rows =$result->RecordCount();
	
		//Page limit
		//$sqlscript.= " limit ". ($pageStart-1)*$list_page. ", " . $list_page;
		//paging
		//$result = $this->ExecuteData($sqlscript);		
		
		$totalpage=1;
		if ($rows>0){
			$rt = $rows%$list_page;
			
			if($rt!=0) {
				$totalpage = floor($rows/$list_page)+1;
			}
			else {
				$totalpage = floor($rows/$list_page);
			}
		}
		
		$this->rowCount=$rows;
		$this->totalpage=$totalpage;	
		
		return $result;
				
	}
	function getStockByID($pid=0,$bid=0){
		global $list_page;
		$sqlscript= "select p.ID,b.BranchName ,s.BranchID , p.ProductName, Category, c.CatName , p.Type"
				.", t.Type ProductType ,s.ProductID "
				.", un.Unit , s.Amount, s.MainAmt as mAmount "
				.",  subun.Unit as SubUnit, p.Scale "
				.", p.Price as Sell_Price , p.Cost_Price, p.Cost_branch  "
				.", IsStock , IsPremium , IsPOS, LimitNumber"
				." From tb_stock_product s "
				." JOIN tb_branch b on b.ID=s.BranchID "
				." JOIN tb_product p on s.ProductID=p.ID "
				." LEFT JOIN tb_product_category c on c.CatID=p.Category"
				." LEFT JOIN tb_product_type t on t.ID=p.Type "
				." LEFT JOIN tb_units un on un.ID=p.MainUnit "
				." LEFT JOIN tb_units subun on  subun.ID=p.SubUnit "
				." Where 1=1 and p.IsDeleted=0 ";
		
		$sqlscript.= " and s.ProductID =".$pid." and s.BranchID=".$bid;
		
		//Execute
		$result = $this->ExecuteData($sqlscript);
		
		
		return $result->FetchRow();
				
	}
	//Check
	function checkStock($pid=0, $branchid=0){
		$sql = " select BranchID from tb_stock_product where BranchID=".$branchid." and ProductID=".$pid;
		//print_r($sql);
		$result = $this->ExecuteData($sql);
		$count=$result->RecordCount(); 
		return $count>0?true:false;
	}
	
	function StockUpdate($pid, $branchid, $amt=0, $user=""){
		$scale=$this->convertStock($pid);
		$Main= ($amt - ($amt % $scale)) / $scale;
		$sqlupdate=" update tb_stock_product "
			. " set Amount= ".$amt
			. " , MainAmt= ".$Main
			. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
			. " , UpdatedBy='".$user."'"
			. " Where BranchID=".$branchid 
			. " And ProductID=".$pid;
			
		$this->ExecuteData($sqlupdate);
	}
	function Stock_Set_Treatment_Update($pid, $branchid, $amt=0, $user="",$IsAdd=1){
		 $arSubProduct = $this->getProductList($pid);
		if ($IsAdd==1){
			foreach ( $arSubProduct  as $list){
				$sqlupdate=" update tb_stock_product "
				. " set Amount= Amount + ".($list['Amount'] * $amt)
				. " , MainAmt=((Amount) - ((Amount) %". $list['Scale']."))/".$list['Scale']
				. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
				. " , UpdatedBy='".$user."'"
				. " Where BranchID=".$branchid 
				. " And ProductID=".$list['SubProductID'];
				 
			 $this->ExecuteData($sqlupdate);
			}
		}else{
			foreach ( $arSubProduct  as $list){
				$sqlupdate=" update tb_stock_product "
					. " set Amount= Amount - ".($list['Amount'] * $amt)
					. " , MainAmt= ((Amount) - ((Amount)%".$list['Scale']."))/".$list['Scale']
					. " , UpdatedDate='".date( "Y/m/d H:i:s" )."'"
					. " , UpdatedBy='".$user."'"
					. " Where BranchID=".$branchid 
					. " And ProductID=".$list['SubProductID'];
					
				$this->ExecuteData($sqlupdate);
			}
		}	
		
	}
	function getProductList($pid){
		$sql =" SELECT d.SubProductID , d.Amount , (SELECT Case when Scale=0 or Scale='' or Scale is null THEN 1 else Scale End FROM tb_product a where  a.ID=d.SubProductID ) as Scale
				From tb_product p
				join tb_product_details d on p.ID=d.ProductID
				where p.IsDeleted = 0 and p.ID=".$pid;
				
		$result = $this->ExecuteData($sql);				
		$ar_result= Array();
		while($row=$result->FetchRow()){
			array_push($ar_result, $row);
		}
		 
		return $ar_result; 		
	}
}
?>